﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace UsingSinger
{
    public class SingerService
    {
        private readonly SingersContext _SingersContext;
        //数据上下文，通过构造函数注入 到私有变量_booksContext中
        public SingerService(SingersContext context) => _SingersContext = context;
        //下列所有关于数据库上下文的操作，都是使用私有变量booksContext


        public async Task CreateTheDatabaseAsync()
        {
            //实例化上下文对象

            //context.Database可用于创建和删除数据库，并直接发送SQL语句
            //EnsureCreatedAsync方法确保创建了数据库。如果数据库已经存在，此方法返回false .
            //若数据库不存在，择根据上下文合模型定义创建数据库
            bool created = await _SingersContext.Database.EnsureCreatedAsync();
            //根据created显示数据库是否存在
            string creationInfo = created ? "created" : "exists";
            Console.WriteLine($"database {creationInfo}");

        }
        public async Task AddSingersAsync()
        {
            var b1 = new Singer
            {
               
                SingesName = "薛之谦",
                Album = "绅士",
            };
            var b2 = new Singer
            {
               
                SingesName = "周杰伦",
                Album = "等你下课",
            };
            var b3 = new Singer
            {
               
                SingesName = "房东的猫",
                Album = "云烟成雨",
            };
            var b4 = new Singer
            {
              
                SingesName = "任然",
                Album = "无人之岛",
            };
           
            _SingersContext.AddRange(b1, b2, b3, b4);
            int records = await _SingersContext.SaveChangesAsync();
            Console.WriteLine($"{records} records added");
        }

        public async Task ReadSingersAsync()
        {
            List<Singer> userHomepage = await _SingersContext.Singers.ToListAsync();
            foreach (var b in userHomepage)
            {
                Console.WriteLine($"{b.SingesName} {b.Album}");
            }
            Console.WriteLine();
        }
    }
}
